<script setup lang="ts">
import useRoleStore from "@/pinia/modules/permissions/roleStore/roleStore.ts";
import { ElMessage } from "element-plus";
import { computed, onMounted, reactive, ref } from "vue";
import { storeToRefs } from "pinia";
import { role } from "@/api/permissions/userApi/interface.ts";
import { batchRemoveRoleAPI, deleteRoleAPI, addOrUpdateRoleAPI, fetchPermissionsAPI, doAssignPerAPI } from "@/api/permissions/roleApi/role.ts";

const roleStore = useRoleStore();

const { pageParams, roleList, total } = storeToRefs(roleStore);

const treeRef = ref(null);

/* 权限列表 */
const permissionsList = ref([]);
/* 是否显示和添加或者编辑角色弹框 */
const roleDialog = ref<boolean>(false);
/* 添加角色状态还是编辑角色状态 */
const editRole = ref<boolean>(false);
/* 待批量删除的角色列表 */
const selectionList = ref<role[]>([]);
/* 表单数据对象 */
const formData = reactive<role>({ roleName: "" });
/* 是否显示添加权限的抽屉 */
const drawer = ref<boolean>(false);
/* 存储勾选权限数组id */
const defaultCheckedKeys = ref<number[]>([]);
/* 获取角色列表的回调函数 */
const fetchRoleList = async () => {
  try {
    await roleStore.fetchRoleList();
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};


/* 点击添加角色按钮的回调函数 */
const handleAddRole = () => {
  roleDialog.value = true;
  editRole.value = false;
};

/* 点击编辑角色按钮的回调函数 */
const handleEditRole = (currentRole: role) => {
  roleDialog.value = true;
  editRole.value = true;
  Object.assign(formData, currentRole);
};
/* 点击删除角色按钮的回调函数 */
const handleDeleteRole = async (currentRole: role) => {
  try {
    await deleteRoleAPI(currentRole.id);
    await fetchRoleList();
    ElMessage.success("删除角色成功");
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};

/* 批量删除角色按钮的回调函数 */
const batchRemoveRole = async () => {
  try {
    await batchRemoveRoleAPI(selectionList.value.map(item => item.id));
    await fetchRoleList();
    ElMessage.success("批量删除角色成功");
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};

/* 确定按钮的回调函数(添加或者编辑角色) */
const handleRoleSubmit = async () => {
  try {
    await addOrUpdateRoleAPI(formData);
    await fetchRoleList();
    roleDialog.value = false;
    ElMessage.success(editRole.value ? "编辑角色成功" : "添加角色成功");
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};

/* 点击搜索按钮的回调函数 */
const handleSearch = () => {
  fetchRoleList();
};

/* 点击重置按钮的回调函数 */
const handleReset = () => {
  pageParams.value.page = 1;
  pageParams.value.limit = 10;
  pageParams.value.roleName = undefined;
  fetchRoleList();
};

/* 对话框关闭时的回调函数 */
const handleDialogClose = () => {
  clearFormData();
};

const clearFormData = () => {
  formData.id = "";
  formData.roleName = "";
  formData.createTime = "";
  formData.updateTime = "";
  formData.remark = null;
};
/* 表格的复选框选中selection-change事件 */
const selectionChange = (selection: role[]) => {
  selectionList.value = selection;
};

/* 分页器size发生变化的回调函数 */
const handleSizeChange = () => {
  fetchRoleList();
};
/* 分页器page发生变化的回调函数 */
const handleCurrentChange = () => {
  fetchRoleList();
};

const handleSubmitPer = async () => {
  const params = {
    roleId: formData.id,
    permissionId: treeRef.value.getCheckedKeys().join(),
  };
  try {
    await doAssignPerAPI(params);
    ElMessage.success("给角色分配权限成功");
    drawer.value = false;
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};


/* 点击分配权限按钮的回调函数 */
const handleAssignPerm = async (currentRole: role) => {
  const { data } = await fetchPermissionsAPI(currentRole.id);
  Object.assign(formData, currentRole);
  permissionsList.value = data;
  defaultCheckedKeys.value = filterDefaultCheckedKeys(permissionsList.value, []);
  drawer.value = true;
};

const filterDefaultCheckedKeys = (permissionsList: any, initArr: any) => {
  permissionsList.forEach(item => {
    if (item.select && item.level === 4) {
      initArr.push(item.id);
    }
    if (item.children && item.children.length !== 0) {
      filterDefaultCheckedKeys(item.children, initArr);
    }
  });
  return initArr;
};
const roleTitle = computed(() => editRole.value ? "编辑角色" : "添加角色");
onMounted(() => {
  fetchRoleList();
});
</script>

<template>
  <div class="role">
    <el-card>
      <el-form label-width="80px" inline class="form">
        <el-form-item label="角色搜索">
          <el-input placeholder="请输入角色名称" v-model="pageParams.roleName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button type="warning" icon="InfoFilled" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" icon="Plus" @click="handleAddRole">添加角色</el-button>
      <el-button type="info" icon="Delete" @click="batchRemoveRole">批量删除角色</el-button>

      <el-table border stripe :data="roleList" @selection-change="selectionChange">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
        <el-table-column label="角色ID" prop="id" align="center" width="80px"></el-table-column>
        <el-table-column label="角色名称" prop="roleName" align="center"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-button type="primary" icon="Position" @click="handleAssignPerm(row)">分配权限</el-button>
            <el-button type="warning" icon="Edit" @click="handleEditRole(row)">编辑角色</el-button>
            <el-button type="danger" icon="Delete" @click="handleDeleteRole(row)">删除角色</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageParams.page" v-model:page-size="pageParams.limit"
        :page-sizes="[10, 20, 30, 40]" background
        layout="total, sizes, prev, pager, next, jumper"
        :total="Number(total||0)" @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <el-dialog v-model="roleDialog" :title="roleTitle" @close="handleDialogClose">
      <el-form :model="formData" label-width="80px">
        <el-form-item label="角色名称">
          <el-input placeholder="输入角色名称" v-model="formData.roleName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="roleDialog = false">取消</el-button>
        <el-button type="primary" @click="handleRoleSubmit">确定</el-button>
      </span>
      </template>
    </el-dialog>

    <el-drawer v-model="drawer" title="角色分配权限" @close="clearFormData()">
      <el-tree :props="{ label: 'name',children: 'children',}" :data="permissionsList" show-checkbox node-key="id" default-expand-all :default-checked-keys="defaultCheckedKeys" ref="treeRef" />
      <template #footer>
        <el-button>取消</el-button>
        <el-button type="primary" @click="handleSubmitPer">保存</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.role {
  .el-card {
    margin-bottom: 10px;

    .form {
      display: flex;
      justify-content: space-between;
    }

    .el-table {
      margin: 10px 0;
    }

    .el-pagination {
      display: flex;
      justify-content: center;
    }
  }

}
</style>
